package com.qingyun.customview.dragview

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.ViewCompat
import androidx.customview.widget.ViewDragHelper

class DragViewGroup @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : FrameLayout(context, attrs, defStyleAttr) {
    private lateinit var mMainView: View
    private lateinit var mMenuView: View
    private val callback: ViewDragHelper.Callback = object : ViewDragHelper.Callback() {
        override fun tryCaptureView(
            child: View,
            pointerId: Int,
        ): Boolean {
            return child == mMainView
        }

        override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
            return 0
        }

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            return left
        }

        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            super.onViewReleased(releasedChild, xvel, yvel)
           if (mMainView.left < 500) {
               mDragHelper.smoothSlideViewTo(mMainView, 0, 0)
               ViewCompat.postInvalidateOnAnimation(this@DragViewGroup)
           }else{
               mDragHelper.smoothSlideViewTo(mMainView, 300, 0)
               ViewCompat.postInvalidateOnAnimation(this@DragViewGroup)
           }
        }
    }
    private val mDragHelper = ViewDragHelper.create(this, callback)

    override fun onFinishInflate() {
        super.onFinishInflate()
        mMenuView = getChildAt(0)
        mMainView = getChildAt(1)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        return mDragHelper.shouldInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        mDragHelper.processTouchEvent(event)
        return true
    }

    override fun computeScroll() {
        super.computeScroll()
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this)
        }
    }
}